package com.bear.atlassianmcp.confluence.service;

import com.bear.atlassianmcp.confluence.config.ConfluenceProperties;
import com.bear.atlassianmcp.confluence.model.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.model.ToolContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Confluence核心服务类
 * 提供Confluence API的核心功能
 */
@Service
public class ConfluenceService {

    private static final Logger logger = LoggerFactory.getLogger(ConfluenceService.class);

    private final RestTemplate restTemplate;
    private final ConfluenceAuthService authService;
    private final ConfluenceProperties confluenceProperties;

    @Autowired
    public ConfluenceService(@Qualifier("confluenceRestTemplate") RestTemplate restTemplate,
                           ConfluenceAuthService authService,
                           ConfluenceProperties confluenceProperties) {
        this.restTemplate = restTemplate;
        this.authService = authService;
        this.confluenceProperties = confluenceProperties;
    }

    /*@PostConstruct
    public void init() {
        // 验证认证配置
        authService.validateAuthConfiguration();
        logger.info("ConfluenceService initialized successfully for base URL: {}", 
                   confluenceProperties.getBaseUrl());
    }*/

    /**
     * 获取页面详情（支持ToolContext）
     *
     * @param pageId 页面ID
     * @param toolContext 工具上下文，用于获取请求头中的授权信息
     * @return ConfluencePage对象
     */
    public ConfluencePage getPage(String pageId, ToolContext toolContext) {
        logger.debug("Getting page: {}", pageId);

        Map<String, String> params = new HashMap<>();
        params.put("expand", confluenceProperties.getExpand());
        String queryParam = params.entrySet().stream()
                .map(entry -> entry.getKey() + "=" + entry.getValue())
                .collect(Collectors.joining("&"));
        String url = authService.getContentApiBaseUrl() + "/" + pageId + "?" + queryParam;

        try {
            HttpEntity<String> entity = new HttpEntity<>(authService.createAuthHeaders(toolContext, url, HttpMethod.GET.name()));
            ResponseEntity<ConfluencePage> response = restTemplate.exchange(
                url, HttpMethod.GET, entity, ConfluencePage.class);

            ConfluencePage page = response.getBody();
            logger.info("Successfully retrieved page: {}", pageId);
            return page;

        } catch (Exception e) {
            logger.error("Failed to get page {}: {}", pageId, e.getMessage());
            throw new RuntimeException("Failed to get page: " + e.getMessage(), e);
        }
    }

    /**
     * 获取所有空间列表（支持ToolContext）
     *
     * @param toolContext 工具上下文，用于获取请求头中的授权信息
     * @return 空间列表
     */
    public List<ConfluenceSpace> getSpaces(ToolContext toolContext) {
        logger.debug("Getting all spaces");

        Map<String, String> params = new HashMap<>();
        params.put("limit", String.valueOf(confluenceProperties.getMaxResults()));
        params.put("expand", "description.plain");
        String queryParam = params.entrySet().stream()
                .map(entry -> entry.getKey() + "=" + entry.getValue())
                .collect(Collectors.joining("&"));
        String url = authService.getSpaceApiBaseUrl() + "?" + queryParam;

        logger.debug("Confluence API URL: {}", url);
        logger.debug("Confluence base URL: {}", confluenceProperties.getBaseUrl());

        try {
            HttpEntity<String> entity = new HttpEntity<>(authService.createAuthHeaders(toolContext, url, HttpMethod.GET.name()));
            logger.debug("Making request to Confluence API...");

            ResponseEntity<ConfluenceSpaceListResponse> response = restTemplate.exchange(
                url, HttpMethod.GET, entity, ConfluenceSpaceListResponse.class);

            logger.debug("Response status: {}", response.getStatusCode());

            List<ConfluenceSpace> spaces = response.getBody().getResults();
            logger.info("Successfully retrieved {} spaces", spaces.size());
            return spaces;

        } catch (Exception e) {
            logger.error("Failed to get spaces from URL: {}", url);
            logger.error("Error details: {}", e.getMessage(), e);
            throw new RuntimeException("Failed to get spaces: " + e.getMessage(), e);
        }
    }

    /**
     * 获取指定空间详情（支持ToolContext）
     *
     * @param spaceKey 空间键值
     * @param toolContext 工具上下文，用于获取请求头中的授权信息
     * @return ConfluenceSpace对象
     */
    public ConfluenceSpace getSpace(String spaceKey, ToolContext toolContext) {
        logger.debug("Getting space: {}", spaceKey);

        Map<String, String> params = new HashMap<>();
        params.put("expand", "description.plain");
        String queryParam = params.entrySet().stream()
                .map(entry -> entry.getKey() + "=" + entry.getValue())
                .collect(Collectors.joining("&"));
        String url = authService.getSpaceApiBaseUrl() + "/" + spaceKey + "?" + queryParam;

        try {
            HttpEntity<String> entity = new HttpEntity<>(authService.createAuthHeaders(toolContext, url, HttpMethod.GET.name()));
            ResponseEntity<ConfluenceSpace> response = restTemplate.exchange(
                url, HttpMethod.GET, entity, ConfluenceSpace.class);

            ConfluenceSpace space = response.getBody();
            logger.info("Successfully retrieved space: {}", spaceKey);
            return space;

        } catch (Exception e) {
            logger.error("Failed to get space {}: {}", spaceKey, e.getMessage());
            throw new RuntimeException("Failed to get space: " + e.getMessage(), e);
        }
    }

    /**
     * 搜索内容（支持ToolContext）
     *
     * @param query 搜索查询
     * @param maxResults 最大结果数
     * @param toolContext 工具上下文，用于获取请求头中的授权信息
     * @return 搜索结果
     */
    public ConfluenceSearchResult searchContent(String query, Integer maxResults, ToolContext toolContext) {
        logger.debug("Searching content with query: {}", query);

        if (maxResults == null) {
            maxResults = confluenceProperties.getMaxResults();
        }
        Map<String, String> params = new HashMap<>();
        params.put("cql", query);
        params.put("limit", String.valueOf(maxResults));
        params.put("expand", "content.space,content.version");
        String queryParam = params.entrySet().stream()
                .map(entry -> entry.getKey() + "=" + entry.getValue())
                .collect(Collectors.joining("&"));
        String url = authService.getApiBaseUrl() + "?" + queryParam;
        try {
            HttpEntity<String> entity = new HttpEntity<>(authService.createAuthHeaders(toolContext, url, HttpMethod.GET.name()));
            ResponseEntity<ConfluenceSearchResult> response = restTemplate.exchange(
                url, HttpMethod.GET, entity, ConfluenceSearchResult.class);

            ConfluenceSearchResult result = response.getBody();
            logger.info("Successfully searched content: {} results", result.getSize());
            return result;

        } catch (Exception e) {
            logger.error("Failed to search content: {}", e.getMessage());
            throw new RuntimeException("Failed to search content: " + e.getMessage(), e);
        }
    }

    /**
     * 获取空间中的页面（支持ToolContext）
     *
     * @param spaceKey 空间键值
     * @param maxResults 最大结果数
     * @param toolContext 工具上下文，用于获取请求头中的授权信息
     * @return 页面列表
     */
    public List<ConfluencePage> getSpacePages(String spaceKey, Integer maxResults, ToolContext toolContext) {
        logger.debug("Getting pages for space: {}", spaceKey);

        if (maxResults == null) {
            maxResults = confluenceProperties.getMaxResults();
        }

        Map<String, String> params = new HashMap<>();
        params.put("spaceKey", spaceKey);
        params.put("type", "page");
        params.put("limit", String.valueOf(maxResults));
        params.put("expand", "space,version");
        String queryParam = params.entrySet().stream()
                .map(entry -> entry.getKey() + "=" + entry.getValue())
                .collect(Collectors.joining("&"));
        String url = authService.getContentApiBaseUrl() + "?" + queryParam;

        try {
            HttpEntity<String> entity = new HttpEntity<>(authService.createAuthHeaders(toolContext, url, HttpMethod.GET.name()));
            ResponseEntity<ConfluencePageListResponse> response = restTemplate.exchange(
                url, HttpMethod.GET, entity, ConfluencePageListResponse.class);

            List<ConfluencePage> pages = response.getBody().getResults();
            logger.info("Successfully retrieved {} pages for space {}", pages.size(), spaceKey);
            return pages;

        } catch (Exception e) {
            logger.error("Failed to get pages for space {}: {}", spaceKey, e.getMessage());
            throw new RuntimeException("Failed to get space pages: " + e.getMessage(), e);
        }
    }

    /**
     * 测试Confluence连接
     *
     * @return 连接测试结果消息
     */
    public String testConnection(ToolContext toolContext) {
        logger.debug("Testing Confluence connection");

        try {
            // 直接尝试获取空间列表来测试连接，这是最简单可靠的方法
            List<ConfluenceSpace> spaces = getSpaces(toolContext);
            String message = String.format("Connection successful! Found %d spaces", spaces.size());
            logger.info("Confluence connection test successful");
            return message;

        } catch (Exception e) {
            logger.error("Confluence connection test failed", e);
            throw new RuntimeException("Connection test failed: " + e.getMessage(), e);
        }
    }

    /**
     * 创建新页面（支持ToolContext）
     *
     * @param title 页面标题
     * @param content 页面内容（Storage格式）
     * @param spaceKey 空间键值
     * @param parentId 父页面ID（可选）
     * @param toolContext 工具上下文，用于获取请求头中的授权信息
     * @return 创建的页面对象
     */
    public ConfluencePage createPage(String title, String content, String spaceKey, String parentId, ToolContext toolContext) {
        logger.debug("Creating page: {} in space: {}", title, spaceKey);

        String url = authService.getContentApiBaseUrl();

        try {
            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("type", "page");
            requestBody.put("title", title);
            requestBody.put("status", "current");

            // 设置空间
            Map<String, Object> space = new HashMap<>();
            space.put("key", spaceKey);
            requestBody.put("space", space);

            // 设置内容
            Map<String, Object> body = new HashMap<>();
            Map<String, Object> storage = new HashMap<>();
            storage.put("value", content);
            storage.put("representation", "storage");
            body.put("storage", storage);
            requestBody.put("body", body);

            // 设置父页面（如果提供）
            if (parentId != null && !parentId.trim().isEmpty()) {
                Map<String, Object> parent = new HashMap<>();
                parent.put("id", parentId);
                requestBody.put("ancestors", Arrays.asList(parent));
            }

            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, authService.createAuthHeaders(toolContext, url, HttpMethod.POST.name()));
            ResponseEntity<String> response = restTemplate.exchange(
                url, HttpMethod.POST, entity, String.class);

            // 手动解析响应以避免JSON反序列化问题
            String responseBody = response.getBody();
            logger.debug("Create page response: {}", responseBody);

            // 创建一个简单的页面对象
            ConfluencePage page = new ConfluencePage();

            // 从响应中提取基本信息
            if (responseBody != null && responseBody.contains("\"id\":")) {
                String id = extractJsonValue(responseBody, "id");
                String actualTitle = extractJsonValue(responseBody, "title");
                String status = extractJsonValue(responseBody, "status");

                page.setId(id);
                page.setTitle(actualTitle != null ? actualTitle : title);
                page.setStatus(status != null ? status : "current");
                page.setType("page");

                logger.info("Successfully created page: {} with ID: {}", page.getTitle(), page.getId());
                return page;
            } else {
                throw new RuntimeException("Invalid response format");
            }

        } catch (Exception e) {
            logger.error("Failed to create page {}: {}", title, e.getMessage());
            throw new RuntimeException("Failed to create page: " + e.getMessage(), e);
        }
    }

    /**
     * 更新页面（支持ToolContext）
     *
     * @param pageId 页面ID
     * @param title 新标题
     * @param content 新内容（Storage格式）
     * @param versionNumber 版本号（必须递增）
     * @param toolContext 工具上下文，用于获取请求头中的授权信息
     * @return 更新后的页面对象
     */
    public ConfluencePage updatePage(String pageId, String title, String content, Integer versionNumber, ToolContext toolContext) {
        logger.debug("Updating page: {}", pageId);

        String url = authService.getContentApiBaseUrl() + "/" + pageId;

        try {
            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("id", pageId);
            requestBody.put("type", "page");
            requestBody.put("title", title);
            requestBody.put("status", "current");

            // 设置版本
            Map<String, Object> version = new HashMap<>();
            version.put("number", versionNumber);
            requestBody.put("version", version);

            // 设置内容
            Map<String, Object> body = new HashMap<>();
            Map<String, Object> storage = new HashMap<>();
            storage.put("value", content);
            storage.put("representation", "storage");
            body.put("storage", storage);
            requestBody.put("body", body);

            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, authService.createAuthHeaders(toolContext, url, HttpMethod.PUT.name()));
            ResponseEntity<ConfluencePage> response = restTemplate.exchange(
                url, HttpMethod.PUT, entity, ConfluencePage.class);

            ConfluencePage page = response.getBody();
            logger.info("Successfully updated page: {}", pageId);
            return page;

        } catch (Exception e) {
            logger.error("Failed to update page {}: {}", pageId, e.getMessage());
            throw new RuntimeException("Failed to update page: " + e.getMessage(), e);
        }
    }

    /**
     * 删除页面（支持ToolContext）
     *
     * @param pageId 页面ID
     * @param toolContext 工具上下文，用于获取请求头中的授权信息
     * @return 删除结果消息
     */
    public String deletePage(String pageId, ToolContext toolContext) {
        logger.debug("Deleting page: {}", pageId);

        String url = authService.getContentApiBaseUrl() + "/" + pageId;

        try {
            HttpEntity<String> entity = new HttpEntity<>(authService.createAuthHeaders(toolContext, url, HttpMethod.DELETE.name()));
            ResponseEntity<String> response = restTemplate.exchange(
                url, HttpMethod.DELETE, entity, String.class);

            logger.info("Successfully deleted page: {}", pageId);
            return "页面已成功删除";

        } catch (Exception e) {
            logger.error("Failed to delete page {}: {}", pageId, e.getMessage());
            throw new RuntimeException("Failed to delete page: " + e.getMessage(), e);
        }
    }

    /**
     * 获取页面详细内容（包含完整内容）
     *
     * @param pageId 页面ID
     * @return 页面对象
     */
    public ConfluencePage getPageContent(String pageId, ToolContext toolContext) {
        logger.debug("Getting page content: {}", pageId);

        Map<String, String> params = new HashMap<>();
        params.put("expand", "body.storage,body.view,space,version,ancestors");
        String queryParam = params.entrySet().stream()
                .map(entry -> entry.getKey() + "=" + entry.getValue())
                .collect(Collectors.joining("&"));
        String url = authService.getContentApiBaseUrl() + "/" + pageId + "?" + queryParam;

        try {
            HttpEntity<String> entity = new HttpEntity<>(authService.createAuthHeaders(toolContext, url, HttpMethod.GET.name()));
            ResponseEntity<ConfluencePage> response = restTemplate.exchange(
                url, HttpMethod.GET, entity, ConfluencePage.class);

            ConfluencePage page = response.getBody();
            logger.info("Successfully retrieved page content: {}", pageId);
            return page;

        } catch (Exception e) {
            logger.error("Failed to get page content {}: {}", pageId, e.getMessage());
            throw new RuntimeException("Failed to get page content: " + e.getMessage(), e);
        }
    }

    /**
     * 根据标题和空间获取页面
     *
     * @param title 页面标题
     * @param spaceKey 空间键值
     * @return 页面对象
     */
    public ConfluencePage getPageByTitle(String title, String spaceKey, ToolContext toolContext) {
        logger.debug("Getting page by title: {} in space: {}", title, spaceKey);
        Map<String, String> params = new HashMap<>();
        params.put("type", "page");
        params.put("spaceKey", spaceKey);
        params.put("title", title);
        params.put("expand", "body.storage,body.view,space,version,ancestors");
        String queryParam = params.entrySet().stream()
                .map(entry -> entry.getKey() + "=" + entry.getValue())
                .collect(Collectors.joining("&"));
        String url = authService.getContentApiBaseUrl() + "?" + queryParam;
        try {
            HttpEntity<String> entity = new HttpEntity<>(authService.createAuthHeaders(toolContext, url, HttpMethod.GET.name()));
            ResponseEntity<ConfluencePageListResponse> response = restTemplate.exchange(
                url, HttpMethod.GET, entity, ConfluencePageListResponse.class);

            List<ConfluencePage> pages = response.getBody().getResults();
            if (pages.isEmpty()) {
                throw new RuntimeException("Page not found with title: " + title);
            }

            ConfluencePage page = pages.get(0);
            logger.info("Successfully retrieved page by title: {}", title);
            return page;

        } catch (Exception e) {
            logger.error("Failed to get page by title {}: {}", title, e.getMessage());
            throw new RuntimeException("Failed to get page by title: " + e.getMessage(), e);
        }
    }

    /**
     * 获取页面的子页面
     *
     * @param pageId 父页面ID
     * @param maxResults 最大结果数
     * @return 子页面列表
     */
    public List<ConfluencePage> getChildPages(String pageId, Integer maxResults, ToolContext toolContext) {
        logger.debug("Getting child pages for page: {}", pageId);

        if (maxResults == null) {
            maxResults = confluenceProperties.getMaxResults();
        }

        Map<String, String> params = new HashMap<>();
        params.put("limit", String.valueOf(maxResults));
        params.put("expand", "space,version");
        String queryParam = params.entrySet().stream()
                .map(entry -> entry.getKey() + "=" + entry.getValue())
                .collect(Collectors.joining("&"));
        String url = authService.getContentApiBaseUrl() + "/" + pageId + "/child/page" + "?" + queryParam;

        try {
            HttpEntity<String> entity = new HttpEntity<>(authService.createAuthHeaders(toolContext, url, HttpMethod.GET.name()));
            ResponseEntity<ConfluencePageListResponse> response = restTemplate.exchange(
                url, HttpMethod.GET, entity, ConfluencePageListResponse.class);

            List<ConfluencePage> pages = response.getBody().getResults();
            logger.info("Successfully retrieved {} child pages for page {}", pages.size(), pageId);
            return pages;

        } catch (Exception e) {
            logger.error("Failed to get child pages for page {}: {}", pageId, e.getMessage());
            throw new RuntimeException("Failed to get child pages: " + e.getMessage(), e);
        }
    }

    /**
     * 添加页面评论
     *
     * @param pageId 页面ID
     * @param comment 评论内容
     * @return 创建的评论对象
     */
    public ConfluenceComment addComment(String pageId, String comment, ToolContext toolContext) {
        logger.debug("Adding comment to page: {}", pageId);

        String url = authService.getContentApiBaseUrl();

        try {
            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("type", "comment");
            requestBody.put("status", "current");

            // 设置父页面
            Map<String, Object> container = new HashMap<>();
            container.put("id", pageId);
            container.put("type", "page");
            requestBody.put("container", container);

            // 设置评论内容
            Map<String, Object> body = new HashMap<>();
            Map<String, Object> storage = new HashMap<>();
            storage.put("value", comment);
            storage.put("representation", "storage");
            body.put("storage", storage);
            requestBody.put("body", body);

            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, authService.createAuthHeaders(toolContext, url, HttpMethod.POST.name()));
            ResponseEntity<ConfluenceComment> response = restTemplate.exchange(
                url, HttpMethod.POST, entity, ConfluenceComment.class);

            ConfluenceComment commentObj = response.getBody();
            logger.info("Successfully added comment to page: {}", pageId);
            return commentObj;

        } catch (Exception e) {
            logger.error("Failed to add comment to page {}: {}", pageId, e.getMessage());
            throw new RuntimeException("Failed to add comment: " + e.getMessage(), e);
        }
    }

    /**
     * 获取页面评论
     *
     * @param pageId 页面ID
     * @param maxResults 最大结果数
     * @return 评论列表
     */
    public List<ConfluenceComment> getPageComments(String pageId, Integer maxResults, ToolContext toolContext) {
        logger.debug("Getting comments for page: {}", pageId);

        if (maxResults == null) {
            maxResults = confluenceProperties.getMaxResults();
        }

        Map<String, String> params = new HashMap<>();
        params.put("limit", String.valueOf(maxResults));
        params.put("expand", "body.storage,version");
        String queryParam = params.entrySet().stream()
                .map(entry -> entry.getKey() + "=" + entry.getValue())
                .collect(Collectors.joining("&"));
        String url = authService.getContentApiBaseUrl() + "/" + pageId + "/child/comment" + "?" + queryParam;

        try {
            HttpEntity<String> entity = new HttpEntity<>(authService.createAuthHeaders(toolContext, url, HttpMethod.GET.name()));
            ResponseEntity<ConfluenceCommentListResponse> response = restTemplate.exchange(
                url, HttpMethod.GET, entity, ConfluenceCommentListResponse.class);

            List<ConfluenceComment> comments = response.getBody().getResults();
            logger.info("Successfully retrieved {} comments for page {}", comments.size(), pageId);
            return comments;

        } catch (Exception e) {
            logger.error("Failed to get comments for page {}: {}", pageId, e.getMessage());
            throw new RuntimeException("Failed to get page comments: " + e.getMessage(), e);
        }
    }

    /**
     * 添加页面标签
     *
     * @param pageId 页面ID
     * @param labelName 标签名称
     * @return 添加结果消息
     */
    public String addLabel(String pageId, String labelName, ToolContext toolContext) {
        logger.debug("Adding label {} to page: {}", labelName, pageId);

        String url = authService.getContentApiBaseUrl() + "/" + pageId + "/label";

        try {
            // 构建请求体
            Map<String, Object> label = new HashMap<>();
            label.put("name", labelName);
            label.put("prefix", "global");

            List<Map<String, Object>> labels = Arrays.asList(label);

            HttpEntity<List<Map<String, Object>>> entity = new HttpEntity<>(labels, authService.createAuthHeaders(toolContext, url, HttpMethod.POST.name()));
            ResponseEntity<String> response = restTemplate.exchange(
                url, HttpMethod.POST, entity, String.class);

            logger.info("Successfully added label {} to page: {}", labelName, pageId);
            return "标签已成功添加";

        } catch (Exception e) {
            logger.error("Failed to add label {} to page {}: {}", labelName, pageId, e.getMessage());
            throw new RuntimeException("Failed to add label: " + e.getMessage(), e);
        }
    }

    /**
     * 获取页面标签
     *
     * @param pageId 页面ID
     * @return 标签列表
     */
    public List<ConfluenceLabel> getPageLabels(String pageId, ToolContext toolContext) {
        logger.debug("Getting labels for page: {}", pageId);

        String url = authService.getContentApiBaseUrl() + "/" + pageId + "/label";

        try {
            HttpEntity<String> entity = new HttpEntity<>(authService.createAuthHeaders(toolContext, url, HttpMethod.GET.name()));
            ResponseEntity<ConfluenceLabelListResponse> response = restTemplate.exchange(
                url, HttpMethod.GET, entity, ConfluenceLabelListResponse.class);

            List<ConfluenceLabel> labels = response.getBody().getResults();
            logger.info("Successfully retrieved {} labels for page {}", labels.size(), pageId);
            return labels;

        } catch (Exception e) {
            logger.error("Failed to get labels for page {}: {}", pageId, e.getMessage());
            throw new RuntimeException("Failed to get page labels: " + e.getMessage(), e);
        }
    }

    // 内部响应类
    private static class ConfluenceSpaceListResponse {
        private List<ConfluenceSpace> results;

        public List<ConfluenceSpace> getResults() {
            return results;
        }

        public void setResults(List<ConfluenceSpace> results) {
            this.results = results;
        }
    }

    private static class ConfluencePageListResponse {
        private List<ConfluencePage> results;

        public List<ConfluencePage> getResults() {
            return results;
        }

        public void setResults(List<ConfluencePage> results) {
            this.results = results;
        }
    }

    private static class ConfluenceCommentListResponse {
        private List<ConfluenceComment> results;

        public List<ConfluenceComment> getResults() {
            return results;
        }

        public void setResults(List<ConfluenceComment> results) {
            this.results = results;
        }
    }

    private static class ConfluenceLabelListResponse {
        private List<ConfluenceLabel> results;

        public List<ConfluenceLabel> getResults() {
            return results;
        }

        public void setResults(List<ConfluenceLabel> results) {
            this.results = results;
        }
    }

    /**
     * 从JSON字符串中提取指定字段的值
     * 这是一个简单的JSON解析方法，用于避免复杂的反序列化问题
     */
    private String extractJsonValue(String json, String fieldName) {
        try {
            String pattern = "\"" + fieldName + "\"\\s*:\\s*\"([^\"]+)\"";
            java.util.regex.Pattern p = java.util.regex.Pattern.compile(pattern);
            java.util.regex.Matcher m = p.matcher(json);
            if (m.find()) {
                return m.group(1);
            }

            // 尝试数字值
            String numberPattern = "\"" + fieldName + "\"\\s*:\\s*([0-9]+)";
            java.util.regex.Pattern np = java.util.regex.Pattern.compile(numberPattern);
            java.util.regex.Matcher nm = np.matcher(json);
            if (nm.find()) {
                return nm.group(1);
            }
        } catch (Exception e) {
            logger.debug("Failed to extract {} from JSON: {}", fieldName, e.getMessage());
        }
        return null;
    }
}
